//Package api is the definition of an open interface
//Copyright © 2020 Tim_Paik <timpaik@163.com>
package api

import (
	"fmt"
	"os"
	"time"

	"github.com/issue9/is"
)

//Install : Install some packages
func Install(packageName []string, repoPath string) (err error) {
	if is.URL(repoPath) {
		fmt.Println("Updating...")
		err = Update(repoPath, "repo.json")
		if err != nil {
			return err
		}
		repoPath = "./repo.json"
	}

	RepoUpdateTime, err := GetFileModTime(repoPath)
	if err != nil {
		return err
	}

	if (time.Now().Unix() - RepoUpdateTime) > 1800 {
		err = UpdateLocal(repoPath)
		if err != nil {
			return err
		}
	}

	repojson, err := Read(repoPath)
	if err != nil {
		return err
	}

	repo := Repo(repojson)
	for i := 0; i < len(packageName); i++ {
		fmt.Println("Installing " + packageName[i] + " from " + repo.Name + "...")
		Search(packageName[i], repo)
	}
	return nil
}

//Search for packages in repositories
func Search(packageName string, repo Repositories) (err error) {
	fmt.Println(packageName)
	fmt.Println(repo)
	return nil
}

//GetFileModTime : Gets the file modification time
func GetFileModTime(path string) (modtime int64, err error) {
	f, err := os.Open(path)
	defer f.Close()
	if err != nil {
		fmt.Println("Error: Open file error!")
		return time.Now().Unix(), err
	}

	fi, err := f.Stat()
	if err != nil {
		fmt.Println("Error: Stat fileinfo error!")
		return time.Now().Unix(), err
	}

	return fi.ModTime().Unix(), nil
}
